﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Cyberwolf.Modules.PWCAPAdmin.Components;
using Cyberwolf.Modules.PWCAPAdmin.Configuration.DataSets;
using Cyberwolf.Modules.PWCAPAdmin.UserControls;
using DotNetNuke.Common;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.Skins;
using DotNetNuke.UI.Skins.Controls;
using System.IO;
using System.Data;

namespace Cyberwolf.Modules.PWCAPAdmin.Configuration
{
    public partial class Connections : PWCAPAdminBaseClass
    {
        #region Private Variables
        #endregion

        #region Public Properties
        public override MainMenu Menu
        {
            get { return pwMenu; }
        }
        #endregion

        #region Event Handlers
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    // Check settings
                    if (!Utilities.SettingsOK(Settings))
                    {
                        pnPWCAPAdminContainer.Visible = false;
                        Skin.AddModuleMessage(this, Localization.GetString("SettingsError", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                        return;
                    }

                    SetupUI();
                }
            }
            catch (Exception ex)
            {
                Exceptions.ProcessModuleLoadException(this, ex);
            }
        }

        protected void gridConnection_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                foreach (TableCell cell in e.Row.Cells)
                {
                    var link = new HyperLink();
                    link.Text = cell.Text;
                    cell.Controls.Add(link);
                }
            }
        }

        protected void gridConnection_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataRowView item = (DataRowView)e.Row.DataItem;
                TextBox txtConnection_Data = e.Row.FindControl("txtConnection_Data") as TextBox;
                object connection = item["Connection_Data"];
                txtConnection_Data.Text = connection == DBNull.Value ? string.Empty : connection.ToString();
                ImageButton btnDelete = e.Row.FindControl("btnDelete") as ImageButton;
                btnDelete.OnClientClick = Localization.GetString("DeleteConnectionConfirm.Text", LocalResourceFile);
                Image imgEdit = e.Row.FindControl("imgEdit") as Image;
                imgEdit.Attributes["onclick"] = string.Format("openConnection('{0}');", (string)item["Organization_ID"]);
            }
        }

        protected void gridConnection_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if ("remove".Equals(e.CommandName))
                {
                    var responseDoc = this.AppService.GetConnectionInfo(PWSecurityToken.Current.SecurityToken);
                    var appKeys = new DSConnections();
                    using (var sr = new StringReader(responseDoc))
                    {
                        appKeys.ReadXml(sr, XmlReadMode.DiffGram);
                    }

                    var OrganizationID = e.CommandArgument.ToString();
                    var connectionRow = appKeys.PW_Connections.FirstOrDefault(r => OrganizationID.Equals(r.Organization_ID));
                    if (connectionRow == null) return;

                    connectionRow.Delete();

                    using (StringWriter CV = new StringWriter())
                    {
                        appKeys.GetChanges().WriteXml(CV, XmlWriteMode.DiffGram);
                        this.AppService.UpdateConnectionInfo(PWSecurityToken.Current.SecurityToken, CV.ToString());
                    }

                    Page.ClientScript.RegisterStartupScript(this.GetType(), "REFRESH", "window.location='" + Request.RawUrl + "';", true);
                }
            }
            catch (Exception ex)
            {
                this.ErrorFlash = ex.Message;
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            // NoticeFlash
            if (NoticeFlash != null)
            {
                litNoticeFlash.Text = "<div class='fnotice'>" + NoticeFlash + "</div>";
                NoticeFlash = null;
            }

            // ErrorFlash
            if (ErrorFlash != null)
            {
                litErrorFlash.Text = "<div class='ferror'>" + ErrorFlash + "</div>";
                ErrorFlash = null;
            }

            if (DotNetNuke.Framework.AJAX.IsInstalled())
            {
                DotNetNuke.Framework.AJAX.RegisterScriptManager();
            }

            if (!DotNetNuke.UI.Utilities.ClientAPI.IsClientScriptBlockRegistered(Page, "main.js"))
            {
                DotNetNuke.UI.Utilities.ClientAPI.RegisterClientScriptBlock(Page, "main.js", "<script src=\"" + ResolveUrl("../js/main.js") + "\" type=\"text/javascript\"></script>");
            }
        }
        #endregion

        #region Private Methods
        private void SetupUI()
        {
            // Menu Localization
            gridConnection.Caption = Localization.GetString("ConnectionsCaption.Text", LocalResourceFile);
            string sharedResourceFile = string.Format("/DesktopModules/{0}/App_LocalResources/PWCAPAdminShared", this.ModuleConfiguration.DesktopModule.FolderName);

            lnkLogout.Text = Localization.GetString("Logout.Text", sharedResourceFile);

            // Menu Urls

            // Menu Visibility
            try
            {
                var responseDoc = this.AppService.GetConnectionInfo(PWSecurityToken.Current.SecurityToken);
                var appKeys = new DSConnections();
                using (var sr = new StringReader(responseDoc))
                {
                    appKeys.ReadXml(sr, XmlReadMode.DiffGram);
                }
                gridConnection.DataSource = appKeys;
                gridConnection.DataMember = "PW_Connections";
                gridConnection.DataBind();
            }
            catch (Exception e)
            {
                this.ErrorFlash = e.Message;
            }
        }
        #endregion
    }
}